package com.achobeta.recruitment.controller.interact;

import com.achobeta.recruitment.common.AppResult;
import com.achobeta.recruitment.common.ResultCode;
import com.achobeta.recruitment.common.Rule;
import com.achobeta.recruitment.model.Manager;
import com.achobeta.recruitment.model.Message;
import com.achobeta.recruitment.model.Student;
import com.achobeta.recruitment.model.WxUser;
import com.achobeta.recruitment.model.vo.MessageVO;
import com.achobeta.recruitment.service.interact.MessageService;
import com.achobeta.recruitment.utils.CheckUtils;
import com.achobeta.recruitment.utils.LimitUtils;
import com.achobeta.recruitment.utils.MediaUtils;
import com.achobeta.recruitment.utils.SessionUtils;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import io.swagger.annotations.ApiParam;
import lombok.NonNull;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.*;
import org.springframework.web.multipart.MultipartFile;

import javax.servlet.http.HttpServletRequest;
import java.io.IOException;
import java.util.*;

/**
 * Created with IntelliJ IDEA.
 * Description:
 * User: 马拉圈
 * Date: 2023-10-31
 * Time: 19:04
 */
@Slf4j
@RestController
@RequestMapping("/message")
@Api(tags = "消息相关")

public class MessageController {

    @Autowired
    private MessageService messageService;


    @ApiOperation(value = "上传图片", notes = "data为保存的路径，String")
    @PostMapping("/picture")
    public AppResult<String> picture(HttpServletRequest request,
                                     @ApiParam("图片") @NonNull @RequestPart("photo") MultipartFile file) throws IOException {
        CheckUtils.checkNULL(file);
        // 获取当前登录用户
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.UPLOAD_PICTURE_MESSAGE_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 获取一个路径
        String originName = file.getOriginalFilename();
        // 校验类型
        CheckUtils.checkImage(originName.substring(originName.lastIndexOf(".")));
        String path = MediaUtils.getImageUniquePath(originName);
        CheckUtils.checkNULL(path);
        // 下载文件
        messageService.loadImage(file, path);
        // 返回成功（路径）
//        path = "http://" + redirectDomain + "/" + path;//改为全路径
        return AppResult.success("上传成功", path);
    }

    @ApiOperation(value = "发送模板消息", notes = "无data")
    @PostMapping("/send")
    public AppResult sendMessage(HttpServletRequest request,
                                 @NonNull @ApiParam("openid") @RequestParam("openid") String openid,
                                 @NonNull @ApiParam("标题") @RequestParam("title") String title,
                                 @NonNull @ApiParam("正文") @RequestParam("content") String content,
                                 @ApiParam("是否默认") @RequestParam(value = "normal", required = false) Byte normal,
                                 @ApiParam("截止时间") @RequestParam(value = "deadline", required = false) Byte deadline,
                                 @ApiParam("链接") @RequestParam(value = "url", required = false) String url,
                                 @ApiParam("图片名") @RequestParam(value = "ticket", required = false) String ticket) {
        // 获取当前登录用户
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.SEND_MODEL_MESSAGE_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 判断四个非必传参数的情况
        List<Integer> list = new ArrayList<>();
        if(normal != null) {
            list.add(1);
        }
        if(deadline != null) {
            list.add(2);
        }
        if(url != null) {
            list.add(3);
            CheckUtils.checkURL(url);
        }
        if(ticket != null) {
            list.add(4);
            CheckUtils.checkFileExists(ticket);
        }
        if(list.size() != 1) {
            log.warn(ResultCode.FAILED_NOT_CHECK_BOX.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_CHECK_BOX);
        }
        // 构造message
        Message message = new Message();
        message.setTicket(ticket);
        message.setNormal(normal);
        message.setDeadline(deadline);
        message.setTitle(title);
        message.setContent(content);
        message.setUrl(url);
        message.setManagerId(manager.getId());
        message.setOpenid(openid);
        message.setDeleteState((byte) 0);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        message.setState((byte) 0);
        switch (list.get(0)) {
            case 1:
                messageService.sendMessageNormal(message);
                break;
            case 2:
                message.setState((byte) 1);//设置为未反馈
                messageService.sendMessageLimit(message);
                break;
            case 3:
                messageService.sendMessageURL(message);
                break;
            case 4:
                messageService.sendMessageWithPhoto(message);
                break;
            default:
                CheckUtils.printWarn(ResultCode.FAILED);
                log.warn(ResultCode.FAILED.toString());
                return AppResult.failed(ResultCode.FAILED);
        }
        // 成功
        return AppResult.success();
    }


    @ApiOperation(value = "群发模板消息", notes = "无data")
    @PostMapping("/mass")
    public AppResult massHair(HttpServletRequest request, @NonNull @RequestBody MessageVO messageVO) {
        // 获取当前登录用户
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.SEND_MODEL_MESSAGE_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 获取消息参数
        String title = messageVO.getTitle();
        String content = messageVO.getContent();
        Byte normal = messageVO.getNormal();
        Byte deadline = messageVO.getDeadline();
        String url = messageVO.getUrl();
        String ticket = messageVO.getTicket();
        // 判断四个非必传参数的情况
        List<Integer> list = new ArrayList<>();
        if(normal != null) {
            list.add(1);
        }
        if(deadline != null) {
            list.add(2);
        }
        if(url != null) {
            list.add(3);
            CheckUtils.checkURL(url);
        }
        if(ticket != null) {
            list.add(4);
            CheckUtils.checkFileExists(ticket);
        }
        if(list.size() != 1) {
            log.warn(ResultCode.FAILED_NOT_CHECK_BOX.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_CHECK_BOX);
        }
        // 构造message
        Message message = new Message();
        message.setTicket(ticket);
        message.setNormal(normal);
        message.setDeadline(deadline);
        message.setTitle(title);
        message.setContent(content);
        message.setUrl(url);
        message.setManagerId(manager.getId());
        message.setDeleteState((byte) 0);
        Date date = new Date();
        message.setCreateTime(date);
        message.setUpdateTime(date);
        message.setState((byte) 0);
        // 对学生表进行去重
        List<Student> students = messageVO.getStudents();
        Set<Student> studentSet = new HashSet<>(students);
        students = new ArrayList<>(studentSet);
        switch (list.get(0)) {
            case 1:
                messageService.sendMessageNormal(students, message);
                break;
            case 2:
                message.setState((byte) 1);//设置为未反馈
                messageService.sendMessageLimit(students, message);
                break;
            case 3:
                messageService.sendMessageURL(students, message);
                break;
            case 4:
                messageService.sendMessageWithPhoto(students, message);
                break;
            default:
                CheckUtils.printWarn(ResultCode.FAILED);
                log.warn(ResultCode.FAILED.toString());
                return AppResult.failed(ResultCode.FAILED);
        }
        // 成功
        return AppResult.success();
    }

    @ApiOperation(value = "获取消息详情", notes = "data为携带接收者名[name]与发起者[managerName]的消息详情信息MessageVO")
    @RequestMapping(value = "/detail", method = {RequestMethod.GET, RequestMethod.POST})
    public AppResult<MessageVO> getDetail(HttpServletRequest request,
                                          @NonNull @ApiParam("消息id") @RequestParam("messageId") Integer messageId) {
        // 获取当前登录用户的信息
        WxUser wxUser = SessionUtils.getWxUser(request);
        String openid = wxUser.getOpenid();
//        String openid = guy;
        // 调用service层
        MessageVO detail = messageService.getDetail(messageId, openid);
        // 校验
        if(detail == null) {
            log.warn(ResultCode.FAILED_NOT_EXISTS.toString());
            return AppResult.failed(ResultCode.FAILED_NOT_EXISTS);
        }
        // 成功返回
        return AppResult.success(detail);
    }

    @ApiOperation(value = "获取一个用户的消息列表", notes = "data为消息列表，一条消息包含内容，发起者，接收者，可能有回复的反馈消息")
    @RequestMapping(value = "/list", method = {RequestMethod.GET, RequestMethod.POST})
    public AppResult<List<MessageVO>> selectMessageByOpenid(HttpServletRequest request,
                                                            @NonNull @ApiParam("openid") @RequestParam("openid") String openid) {
        // 获取当前登录的管理员账号
        Manager manager = SessionUtils.getManager(request);
        // 判断是否有权限
        if(!LimitUtils.hasPower(manager, Rule.MESSAGE_LIST_RULE)) {
            log.warn(ResultCode.FAILED_MANAGER_NOT_POWERS.toString());
            return AppResult.failed(ResultCode.FAILED_MANAGER_NOT_POWERS);
        }
        // 调用dao层
        List<MessageVO> messageVOS = messageService.selectMessageByOpenId(openid);
        messageVOS = messageVOS == null ? new ArrayList<>() : messageVOS;
        // 结果为空集合也是合理的
        return AppResult.success(messageVOS);
    }

}
